﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using com.google.zxing;
using com.google.zxing.common;
using com.google.zxing.qrcode;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Media;
using Microsoft.Xna.Framework.Media;
using MicroMsg.sdk;
using Microsoft.Phone.Tasks;
using System.Threading.Tasks;
using Windows.Phone.Storage.SharedAccess;
using Windows.Storage;
using ScannerDemo;
using ScannerDemo.common;

namespace ScannerDemo
{
    
    public partial class GenerateResult : PhoneApplicationPage
    {
        private WriteableBitmap _wb;
        string tempString = "";
        string path;
        int flag;
        Picture pic;
        ApplicationBarIconButton appBarIconBtnShareQR = new ApplicationBarIconButton(new Uri("/icons/share.png", UriKind.Relative));
        ApplicationBarIconButton appBarIconBtnSave = new ApplicationBarIconButton(new Uri("/icons/save.png", UriKind.Relative));
        ApplicationBarIconButton appBarIconBtnScan = new ApplicationBarIconButton(new Uri("/icons/scan icon.png", UriKind.Relative));
        //DataValidator dataValidator = new DataValidator();
        public GenerateResult()
        {
            InitializeComponent();

        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                #region C#生成ApplicationBar已经相关的Button和事件.
                ApplicationBar = new ApplicationBar();

                //ApplicationBarIconButton appBarIconBtnQR = new ApplicationBarIconButton(new Uri("/icons/appbar.refresh.rest.png", UriKind.Relative));
                appBarIconBtnShareQR.Text = "分享";
                appBarIconBtnShareQR.Click += new EventHandler(ApplicationBar_Share_Click);
                //appBarIconBtnShareQR.IsEnabled = false;
                ApplicationBar.Buttons.Add(appBarIconBtnShareQR);

                appBarIconBtnSave.Text = "保存";
                appBarIconBtnSave.Click += new EventHandler(ApplicationBar_Save_Click);
                //appBarIconBtnShareQR.IsEnabled = false;
                ApplicationBar.Buttons.Add(appBarIconBtnSave);



                appBarIconBtnScan.Text = "扫描";
                appBarIconBtnScan.Click += new EventHandler(ApplicationBar_StartPage_Click);
                ApplicationBar.Buttons.Add(appBarIconBtnScan);

                ApplicationBar.IsVisible = true;

                #endregion

            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }


        
        
        

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            flag = 0;
            //if ((NavigationContext.QueryString.Count > 0))
            //{
                tempString = App.PublicText;
                //NavigationContext.QueryString.TryGetValue("text", out tempString);
            //}
            QRCodeWriter qrWrite = new QRCodeWriter();
            int width = 300;
            int height = 300;

            if ((tempString == null)||(tempString==""))
                return;
            //write the new generated qrcode to the xml file
            MainPage a = new MainPage();
            String type = "2";
            a.write_xml(tempString,type);
            ByteMatrix bm = qrWrite.encode(tempString, BarcodeFormat.QR_CODE, width, height);
            //var asBitmap = bm.ToBitmap(BarcodeFormat.QR_CODE, textInput.Text);
            var asBitmap = ConvertByteMartixToWriteableBitmap(bm);
            _wb = asBitmap;
            this.QrImg.Source = asBitmap;
        }
        public WriteableBitmap ConvertByteMartixToWriteableBitmap(ByteMatrix bm)
        {

            WriteableBitmap wb = new WriteableBitmap(bm.Width, bm.Height);



            for (int x = 0; x <= wb.PixelWidth - 1; x++)
            {



                for (int y = 0; y <= wb.PixelHeight - 1; y++)
                {

                    if (bm.Array[y][x] == -1)
                    {

                        //白色

                        wb.Pixels[wb.PixelWidth * y + x] = BitConverter.ToInt32(BitConverter.GetBytes(0xffffffff), 0);



                    }

                    else
                    {

                        //黑色

                        wb.Pixels[wb.PixelWidth * y + x] = BitConverter.ToInt32(BitConverter.GetBytes(0xff000000), 0);



                    }

                }

            }

            return wb;


        }
        private void ApplicationBar_Share_Click(object sender, EventArgs e)
        {
            /*string AppID = "wx124d4f2786d28ebc";
            int scene = SendMessageToWX.Req.WXSceneChooseByUser;
            WXBaseMessage message = null;

            MemoryStream ms = new MemoryStream();
            _wb.SaveJpeg(ms, _wb.PixelWidth, _wb.PixelHeight, 0, 70);
            byte[] bytes = ms.GetBuffer();  

            WXImageMessage msg = new WXImageMessage();
            msg.Title = "图片";
            msg.Description = "这是一个图片";
            msg.ThumbData = bytes;
            

            //图片的byte[]数据
            msg.ImageData = bytes;

            //图片的网络链接，ImageUrl和ImageData二者取其一，不要同时都填值
            //msg.ImageUrl = "http://soso7.gtimg.cn/sosopic/0/4085165533549977883/150";

            msg.ImageUrl = " ";
            message = msg;
            try
            {
                SendMessageToWX.Req req = new SendMessageToWX.Req(message, scene);
                IWXAPI api = WXAPIFactory.CreateWXAPI(AppID);
                api.SendReq(req);
            }
            catch (WXException ex)
            {
                MessageBox.Show(ex.Message);
                //MessageBox.Show("mmm");
            }*/
            if (flag == 0)
            {
                save_jpeg();
                flag = 1;
            }
            /*
               var bmp = new WriteableBitmap(this.ContentPanel, null);
    var width = (int)bmp.PixelWidth;
    var height = (int)bmp.PixelHeight;
    using (var ms = new MemoryStream(width * height * 4)) {
        bmp.SaveJpeg(ms, width, height, 0, 100);
        ms.Seek(0, SeekOrigin.Begin);
        var lib = new MediaLibrary();
        var picture = lib.SavePicture(string.Format("test.jpg"), ms);
 
        var task = new ShareMediaTask();
 
        task.FilePath = lib.//picture.();
 
        task.Show();

            */
            MessageBox.Show("分享前系统会自动帮您保存到相册！");
            ShareMediaTask shareMediaTask = new ShareMediaTask();
            //string fileName = "saveJPEG.jpg";
            var myStore = IsolatedStorageFile.GetUserStoreForApplication();
            var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
           // shareMediaTask.FilePath = localFolder.Path+"\\"+fileName;
            //shareMediaTask.FilePath = path;
            shareMediaTask.FilePath = path; //+ "\\" + fileName;
            shareMediaTask.Show();


            

        }
        
        private void ApplicationBar_Save_Click(object sender, EventArgs e)
        {
            if (flag == 0)
            {
                if (save_jpeg())
                    MessageBox.Show("保存成功！");
                else
                    MessageBox.Show("保存失败，磁盘空间不足或系统问题！");
                flag = 1;
                appBarIconBtnSave.IsEnabled = false;
            }
           
            
            
           
        }
        public bool save_jpeg()
        {
            // 在独立存储中创建一个临时文件
            try
            {
                string fileName = "myImage.jpg";
                var myStore = IsolatedStorageFile.GetUserStoreForApplication();
                if (myStore.FileExists(fileName))
                    myStore.DeleteFile(fileName);
                IsolatedStorageFileStream myFileStream = myStore.CreateFile(fileName);

                // 将图片保存到独立存储的临时文件

                _wb.SaveJpeg(myFileStream, _wb.PixelWidth, _wb.PixelHeight, 0, 70);
                myFileStream.Close();

                // 打开独立存储中的图片
                myFileStream = myStore.OpenFile(fileName, FileMode.Open, FileAccess.Read);
                string a = "";
                // 将图片保存到“相册”
                MediaLibrary library = new MediaLibrary();
                pic = library.SavePicture("saveJPEG.jpg", myFileStream);

                path = Microsoft.Xna.Framework.Media.PhoneExtensions.MediaLibraryExtensions.GetPath(pic);
                myFileStream.Close();
                myStore.Dispose();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }


        private void ApplicationBar_StartPage_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }
        
    }

     
    //处理微信发出的请求或响应的入口处理函数
    /*public partial class NokiaScannerMsgEntry : WXEntryBasePage
    {
        internal static GetMessageFromWX.Req lastRequest;

        public NokiaScannerMsgEntry()
        {
            InitializeComponent();
        }

        /*
         * 微信拉起App来获得数据的入口
         */
        /*public override void On_GetMessageFromWX_Request(GetMessageFromWX.Req request)
        {
            /*if (request != null)
            {
                lastRequest = request;
                //NavigationService.Navigate(new Uri("/GenerateResult.xaml", UriKind.Relative));
                NavigationService.GoBack();
            }*/
        //}

        /*
        * 发送消息后，微信返回成功或失败的相应，不关注结果goback处理
        */
        /*public override void On_SendMessageToWX_Response(SendMessageToWX.Resp response)
        {
            if (NavigationService.CanGoBack)
            {
                NavigationService.GoBack();
            }
            else
            {
                //NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                NavigationService.GoBack();
                //NavigationService.Navigate(new Uri("/GenerateResult.xaml", UriKind.Relative));
                //NavigationService.RemoveBackEntry();
            }
        }

        /*
         * 可暂忽略的函数，SDK 1.0版本不支持
        * 请求授权后，微信发回的响应数据
        */
        /*public override void On_SendAuth_Response(SendAuth.Resp response)
        {
        }

        /*
         * 可暂忽略的函数
        * 微信请求应用显示特定的消息数据（数据在request.Message中）
        */
        /*public override void On_ShowMessageFromWX_Request(ShowMessageFromWX.Req request)
        {
            
        }
    }*/

    //UriMapperBase继承类，主要逻辑是，判断是微信请求或响应过来后，导向到DemoEntryPage
    class AssociationUriMapper : UriMapperBase
    {
        public override Uri MapUri(Uri uri)
        {
            string tempUri = System.Net.HttpUtility.UrlDecode(uri.ToString());
           // string tempUri = uri.ToString();

            // 根据文件类型打开程序
            if (tempUri.Contains("/FileTypeAssociation"))
            {
                // 获取fileID (after "fileToken=").
                int fileIDIndex = tempUri.IndexOf("fileToken=") + 10;
                string fileID = tempUri.Substring(fileIDIndex);

                // 获取文件名.
                string incommingFileName = SharedStorageAccessManager.GetSharedFileName(fileID);

                // 获取文件后缀
                int extensionIndex = incommingFileName.LastIndexOf('.') + 1;
                string incommingFileType = incommingFileName.Substring(extensionIndex).ToLower();

                // 根据不同文件类型，跳转不同参数的地址
                switch (incommingFileType)
                {
                    case "wx124d4f2786d28ebc":
                        //fileToken参数名不要改，就用这个，不然取不到数据
                        return new Uri("/NokiaScannerMsgEntry.xaml?fileToken=" + fileID, UriKind.Relative);
                       //return new Uri("/HomePagePivot.xaml?fileToken=" + fileID, UriKind.Relative);
                    default:
                        return new Uri("/HomePagePivot.xaml", UriKind.Relative);
                }
            }
            else if (tempUri.Contains("Protocol?encodedLaunchUri=nokiagenqr"))
            {
                int urlIndex = tempUri.IndexOf("nokiagenqr");
                if (urlIndex>0)
                {
                    urlIndex+= 11; // 引号,所以加上10+1
                string url = tempUri.Substring(urlIndex);
                App.PublicText = url;
                }
                return new Uri("/GenerateResult.xaml", UriKind.RelativeOrAbsolute);
            }
            else if (tempUri.Contains("/Protocol"))///Protocol?encodedLaunchUri=nokiascanner%3A
                return new Uri("/MainPage.xaml", UriKind.Relative);   
            else
            {
                return uri;
            }
        }
    }
}